<?php
/**
 * Created by PhpStorm.
 * User: brain
 * Date: 2016/3/25
 * Time: 18:27
 */

namespace App\Kids\Caches;


use App\Common\TableCacher;
use App\Models\Menu;
use p5\objects\ArrayUtils;
use p5\objects\CollectionUtils;

class MenuCacher extends TableCacher
{

    static protected $table = "menu";

    static public function findMenus($menuIds = [])
    {
        $result = [];
        $list = self::all();
        foreach ($list as $line) {
            $menuId = $line["menu_id"];
            if (in_array($menuId, $menuIds)) {
                array_push($result, $line);
            }
        }
        return $result;
    }

    static public function findAdminMenus($properties = [])
    {
        $list = CollectionUtils::findAll(self::all(), $properties);
        return $list;
    }

    static public function findMenu($menuId)
    {
        return self::findOne("menu_id", $menuId);
    }

    static public function findMenuObject($menuId)
    {
        $menu = new Menu();
        $properties = self::findOne("menu_id", $menuId);
        $menu->forceFill($properties);
        return $menu;
    }

    static public function getPublicMenuIds()
    {
        $result = [];
        $list = self::all();
        foreach ($list as $line) {
            $flag = $line["public_flag"];
            if ($flag == 1) {
                array_push($result, $line["menu_id"]);
            }
        }
        return $result;
    }

    static public function explanIds($menuIds)
    {
        $all = [];
        foreach ($menuIds as $menuId) {
            $ids = self::findAncestorIds($menuId);
            $all = array_merge($all, $ids);
        }
        $all = array_values(array_unique($all));
        return $all;
    }

    static public function findAncestorIds($menuId, $includeMySelf = true)
    {
        $ids = [];
        if ($includeMySelf) {
            array_push($ids, $menuId);
        }
        $currentId = $menuId;
        while (true) {
            $menu = self::findMenu($currentId);
            if (empty($menu)) {
                break;
            }
            $parentId = $menu["parent_id"];
            if (empty($parentId) || $parentId == "#") {
                break;
            }
            array_push($ids, $parentId);
            $currentId = $parentId;
        }
        return $ids;
    }

    static public function getLoadSql()
    {
        return "select * from menu order by order_number";
    }
}